Skip to content

feat(annotations): companion app for slide annotations behind the authenticating proxy - #4

Merged
raylim merged 37 commits into
mainfrom
feature/wsi-native-annotation-backend
Nov 12, 2026
Merged

raylim merged 37 commits into
mainfrom
feature/wsi-native-annotation-backend

Conversation

@raylim

@raylim raylim commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Slide annotations for the native OpenSeadragon pathology viewer, served by a companion app that runs from the same image as the pixel server but as its own deployment.

  • app.companion (gunicorn -c python:app.gunicorn_conf app.companion:app): annotation list, create, update and delete for rectangle, polygon, point and freehand geometry; creator/group/public visibility; creator-only changes; atomic optimistic concurrency.
  • The pixel app (app.main, the image's default command) serves no annotation route, so a hostNetwork pixel pod never reads a user header.
  • Storage: SQLite for local development; Postgres/Lakebase for shared deployments (pooled connections, idempotent schema migration).
  • slide_id must be the opaque slide key. Any other value (e.g. a pathology image ID) is rejected with 422 before it reaches storage.

Identity from the authenticating proxy

The companion does no authentication of its own. A reverse proxy authorizes each request with cBioPortal's GET /api/studies/{studyId}/access (session cookie forwarded) and copies X-Auth-Request-User and X-Auth-Request-Study from the 204 response onto the request, replacing any client copy. app.request_identity then requires:

  • X-Auth-Request-Study present and well formed, else 401;
  • studyId in the query string exactly once (names matched case-insensitively, as nginx does) and equal to X-Auth-Request-Study, else 403;
  • the body's study, and the stored row's study for an update or delete, equal to that study, else 403;
  • X-Auth-Request-User present, else 401. Only with ANNOTATION_ALLOW_ANONYMOUS=true (development stacks whose portal has no login) does a request act as ANNOTATION_ANONYMOUS_USER instead.

created_by is the forwarded user: cBioPortal's authentication.getName().

Browser request rules (CSRF)

POST, PUT, PATCH and DELETE must send X-Requested-With: XMLHttpRequest (else 403), Content-Type: application/json when there is a body (else 415), and either no Origin or one that is the request's own host or listed in COMPANION_ALLOWED_ORIGINS (else 403). The companion sends no CORS headers, caps bodies at COMPANION_MAX_BODY_BYTES (4 MiB; 413 above it, including chunked bodies), and marks every response private, no-store.

Lakebase login

With ANNOTATION_DATABASE_PASSWORD_PROVIDER=databricks, each new pool connection logs in with a Lakebase database credential for ANNOTATION_LAKEBASE_INSTANCE. The credential is generated through POST /api/2.0/database/credentials as a service principal (DATABRICKS_HOST, DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET) and cached until 5 minutes before it expires. The request uses the standard library only; no SDK is added. Idle connections close after 300 s, and all connections are replaced every 30 minutes (ANNOTATION_DB_MAX_INACTIVE_CONNECTION_LIFETIME, ANNOTATION_DB_MAX_CONNECTION_AGE_SECONDS). Without a provider, the password in ANNOTATION_DATABASE_URL is used.

Deployment requirements

The companion must be reachable only through the authenticating proxy:

  • run it on the pod network, never hostNetwork;
  • put a NetworkPolicy on it that admits only the ingress controller's namespace;
  • route no Ingress rule to it without the auth subrequest.

The README documents both entrypoints, every environment variable, and example ingress-nginx (auth-url + auth-response-headers, NetworkPolicy) and plain nginx (auth_request + auth_request_set + proxy_set_header) configuration. docker-compose.yml runs the companion on loopback.

Validation

  • uv run pytest: 369 passed. CI security and container-smoke pass.
  • tests/test_companion.py:
    • identity headers present, missing or malformed;
    • repeated, missing or mismatched studyId;
    • anonymous use allowed and refused;
    • CRUD over HTTP recording the forwarded user;
    • a forged study header cannot update or delete another study's row;
    • the CSRF rules, no CORS headers, and the body cap (declared and chunked);
    • the pixel app exposes no annotation route.
  • tests/test_lakebase_credentials.py: the provider is tested against a mocked REST API (M2M token exchange, the credential request, caching and refresh, a personal-token fallback, validation), along with pool wiring and connection recycling.

Related

🤖 Generated with Claude Code

@raylim
raylim force-pushed the feature/wsi-native-annotation-backend branch from 7f9208d to 84e2520 Compare July 21, 2026 21:36
@raylim
raylim force-pushed the feature/wsi-native-annotation-backend branch 2 times, most recently from b82e260 to d3ff4fc Compare August 20, 2026 03:50
raylim and others added 11 commits August 28, 2026 17:48
httpx was only in the dev group but is imported at runtime in auth.py
for async JWKS fetching from Keycloak.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ring

- Dockerfile: mkdir -p /data && chown appuser /data for SQLite volume
- config.py: annotation_db_path, keycloak_jwks_url, annotation_auth_enabled
- main.py: register annotation router, init_annotation_db in lifespan, expand CORS
- docker-compose.yml: annotation_data volume + annotation env vars
- uv.lock: updated for new deps

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
app/auth.py:
- Keycloak JWKS validation with in-memory cache + TTL
- require_user() FastAPI Depends; ANNOTATION_AUTH_ENABLED=false dev escape hatch

app/annotations.py:
- Full W3C-format annotation CRUD (GET/POST/PUT/DELETE)
- SQLite WAL mode, optimistic concurrency via version field
- Creator-only delete, visible_to group filtering

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
These packages were added to pyproject.toml for the annotation API but
uv.lock was not regenerated, causing ModuleNotFoundError on container start.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@raylim
raylim force-pushed the feature/wsi-native-annotation-backend branch from 247554e to b76751f Compare August 28, 2026 21:58
@raylim

raylim commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator Author

Rebuilt this PR on current main, retaining only the annotation-specific implementation now that the base tile-serving contract is merged in #17. The updated head adds complete CRUD/concurrency coverage, uses only cBioPortal-issued study-scoped annotation capabilities, and removes the vulnerable unused python-jose dependency.

Validation on the pushed head: 227 tests passed, the locked dependency audit found no known vulnerabilities, and both GitHub security and container-smoke are green. There are no unresolved non-outdated review threads.

raylim and others added 3 commits September 21, 2026 17:28
- Accept only wsi_auth_version 3. Decrypt the `enc` claim (AES-256-GCM, key
  HKDF-SHA256(secret, "wsi-claim-enc-v3"), AAD = slide_key) and serve the
  tile/thumbnail source from it; X-WSI-Source and ?source= are rejected (400).
  Plaintext image_id/source/source-digest claims are rejected. Decrypted
  claims are cached per token after signature/expiry checks; failures are
  not cached. Previous-secret rotation still works.
- Rate-limit scope uses study_id + slide_key; error/log text never includes
  ids or URIs (FileNotFoundError messages no longer echo source URIs).
- de-id: reject accession numbers in WSI/timeline text columns; opaque
  part/block/specimen keys, image_id and artifact URIs skip only the compact
  YYYYMMDD heuristic; hex source_fingerprint is validated as a digest;
  SLIDE_KEY required on WSI rows; IMAGE_ID(S) forbidden in timeline rows.
- Health/readiness report auth contract 3; readiness expects wsi-serving-v5.
- cryptography is a runtime dependency.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Specimen accession formats are institution-specific, so the open-source
tile server no longer hard-codes one. Remove ACCESSION_PATTERN,
contains_accession and _assert_no_accession, and their uses in WSI and
timeline row validation and the safe-text scan. Data providers enforce
their own accession rules before publishing rows.

Unchanged: v3 token/encrypted-source auth, SLIDE_KEY requirement and
pattern, source_fingerprint digest handling, opaque-key/server-only date
exemptions, IMAGE_ID(S) rejection on timeline rows, date/MRN checks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
raylim and others added 5 commits October 9, 2026 14:04
… version re-checks

validate_wsi_token already rejects any wsi_auth_version other than
WSI_AUTH_VERSION, so the middleware and _authorize_source re-checks could
never fire. The lifespan refuses to start without a valid
WSI_SOURCE_SEAL_KEY, so decode it there once instead of on every request;
an unset key still fails closed (validate_wsi_token rejects it).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…e slideKey regex

validate_artifact_uri never read image_id, and related_identifiers had no
production caller. The timeline slideKey linkout pattern now reuses
SLIDE_KEY_PATTERN, and a stale pipeline-version comment is reworded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… deid

auth.py re-declared the sealed-source alphabet, nonce/tag sizes and a
base64url decoder already defined for the SEALED_SOURCE column check;
import them from app.deid instead (values unchanged). decrypt_sealed_claims
no longer re-validates the seal key, which validate_wsi_token checks first.
Only the sealed claims are forbidden in plaintext; the v2 *_sha256 digest
claims are unreachable since v2 tokens fail the version check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- Fold the wrong-key enc cases (zero key, signing secret) into the
  tampered-enc table; drop the HKDF v3-derivation test and its imports.
- Test auth-version rejection once, in test_auth, parametrized on
  wsi_auth_version; drop the v2/v3 route-level copies.
- Drop the _reject_client_source unit tests (the route test covers them),
  the duplicate decrypted-source policy test, the duplicate valid-key
  readiness test, and the test that only pinned WSI_AUTH_VERSION.
- Share a _request_with_capability helper; build make_token on
  make_raw_token; fix a stale comment.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Rebuild the annotation API on the v4 slide capabilities:

- auth: keep #44's slide capability check unchanged and add
  validate_scoped_capability for the study-scoped tokens cBioPortal issues
  from /access-token?purpose=annotations|agent. They must carry the
  required scopes and must name no slide (no slide_key, enc,
  wsi_auth_version, sealed claims or wsi:read), so they can never open
  tiles and a slide capability can never write annotations. The previous
  auth secret is accepted during rotation, as for tiles.
- annotations: slide_id must be an opaque slide key; image IDs are
  rejected before they reach storage.
- Drop the unauthenticated OncoKB proxy (no viewer caller), the unused
  Keycloak JWKS setting, the Databricks-era association settings, and the
  Lakebase bundle (Databricks tooling left this repo in #42).
- httpx goes back to the dev group; CI publish-workflow changes are left
  to their own PR.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
raylim added a commit that referenced this pull request Oct 9, 2026
- auth: the assistant and research routes use the study-scoped capability
  check from #4 (scoped_user_dependency over validate_scoped_capability),
  with the previous-secret fallback; capabilities now report their scopes.
- agent: slide_id, embedding slide_ids and commit requests must be opaque
  slide keys, so an image ID cannot reach a prompt, a stored proposal or
  the annotation store.
- Drop the OncoKB proxy and the Databricks dev-namespace settings that #4
  and #42 removed; httpx stays a runtime dependency for the QuiltNet
  worker client.
- Tests use slide keys.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@raylim
raylim changed the base branch from main to codex/wsi-deid-slide-key-v3 October 9, 2026 20:18
raylim and others added 6 commits October 13, 2026 13:00
slide_store.resolve_s3_location is the only live copy; nothing calls the
SlideCache module's private duplicate.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
No producer emits slideKey in a timeline LINKOUT (pdm #44 and #45 emit
only specimenKey), so a slideKey value is now scanned like any other
query value.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ests

- fold the unsupported-scheme cases into the outside-policy parametrize
- one parametrized route test for tile and thumbnail decrypted sources
- drop the route-level thumbnail outside-policy twin, the rate-limit
  scope unit test (covered end to end), the rebound-slide-key twin of
  the tampered-enc parametrize, the lru_cache exception test and two
  default-getter config tests

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
lifespan already decodes WSI_SOURCE_SEAL_KEY into _source_seal_key and
refuses to start without it; /ready now validates that value instead of
decoding the setting a second time on every probe.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
raylim added a commit that referenced this pull request Oct 13, 2026
@raylim
raylim added this pull request to stack #45 October 14, 2026 17:11
Base automatically changed from codex/wsi-deid-slide-key-v3 to main October 21, 2026 17:40
Takes main's v4 capability auth, sealed sources, generic resource keys, Z-stack and ETag-safe cache. The study-scoped annotation token checks stay; the slide-key pattern now comes from app/sealed_source.py, and app/deid.py is removed as on main.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
raylim added a commit that referenced this pull request Nov 3, 2026
…nto the research assistant

# Conflicts:
#	app/auth.py
#	app/main.py
aiohttp 3.14.5, certifi 2026.10.23, filelock 4.2.7, msgpack 1.2.4 and pillow 13.0.0 (yarl 1.25.1 follows aiohttp), so the pip-audit step passes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
raylim added a commit that referenced this pull request Nov 3, 2026
raylim and others added 3 commits November 12, 2026 16:38
Brings in the tokenless pixel contract (#49): tiles and thumbnails open
the sealed source with no JWT behind the ingress study check, so the slide
capability middleware is gone. Annotation routes keep validating study
tokens, now from app.study_auth with WSI_AUTH_SECRET / WSI_AUTH_AUDIENCE
read only by that module.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Annotations move out of the pixel app into app.companion, a separate ASGI
app in the same image (gunicorn ... app.companion:app). The pixel app
serves no annotation route and is back to GET-only CORS, so a hostNetwork
pixel pod never trusts a user header.

The companion takes the user and study from X-Auth-Request-User and
X-Auth-Request-Study, which the proxy copies from cBioPortal's
/api/studies/{studyId}/access response (app.request_identity):
- no study header: 401;
- studyId missing, repeated in any case, or not the header study: 403;
- the body's study and an updated or deleted row's study must be the
  header study (403), with no "no study" bypass;
- no user header: 401, or ANNOTATION_ANONYMOUS_USER when
  ANNOTATION_ALLOW_ANONYMOUS=true (development only).
created_by is the forwarded user. Study tokens (WSI_AUTH_SECRET,
WSI_AUTH_AUDIENCE, scopes, ANNOTATION_AUTH_ENABLED) are gone.

Unsafe methods need X-Requested-With: XMLHttpRequest, a JSON body and no
foreign Origin (own host or COMPANION_ALLOWED_ORIGINS); the companion sends
no CORS headers, caps bodies at COMPANION_MAX_BODY_BYTES (4 MiB) and marks
responses no-store. /ready checks annotation storage.

The README documents both entrypoints, the trusted-proxy requirement and
ingress-nginx / nginx examples; docker-compose runs the companion on
loopback.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
ANNOTATION_DATABASE_PASSWORD_PROVIDER=databricks makes the annotation pool
ask app.lakebase_credentials for the password of every new connection: a
Lakebase database credential for ANNOTATION_LAKEBASE_INSTANCE, generated
through POST /api/2.0/database/credentials as a service principal
(DATABRICKS_HOST, DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET; or
DATABRICKS_TOKEN) and cached until five minutes before it expires. Only
the standard library is used, and no token or secret is logged.

The pool closes connections idle for
ANNOTATION_DB_MAX_INACTIVE_CONNECTION_LIFETIME (300 s) and replaces all of
them every ANNOTATION_DB_MAX_CONNECTION_AGE_SECONDS (1800 s), below the
token's hour. A static password in ANNOTATION_DATABASE_URL still works
when no provider is set.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
raylim added a commit that referenced this pull request Nov 12, 2026
…assistant stack

Brings in the tokenless pixel contract (#49) through #4. Pixels open the
sealed source with no JWT; annotation, assistant and research routes keep
validating study tokens in app.study_auth (WSI_AUTH_SECRET,
WSI_AUTH_PREVIOUS_SECRET, WSI_AUTH_AUDIENCE). tools/build_keep_manifest.py
catches InvalidSealedSource.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@raylim raylim changed the title feat(annotations): support the native WSI viewer feat(annotations): companion app for slide annotations behind the authenticating proxy Nov 12, 2026
@raylim
raylim merged commit ef7c50d into main Nov 12, 2026
4 checks passed
raylim added a commit that referenced this pull request Nov 12, 2026
main now carries #4 squashed (ef7c50d); this branch already contains
every #4 commit, so the tree is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant